package com.samsung.service.impl.lottery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.DateUtil;
import com.samsung.dao.lottery.LotteryCandidateMapper;
import com.samsung.dao.lottery.LotteryEventMapper;
import com.samsung.dao.lottery.LotteryItemMapper;
import com.samsung.dao.lottery.LotteryRecordMapper;
import com.samsung.dto.lottery.CandidateDto;
import com.samsung.dto.lottery.EventFormDto;
import com.samsung.dto.lottery.ItemResultDto;
import com.samsung.model.lottery.LotteryCandidate;
import com.samsung.model.lottery.LotteryEvent;
import com.samsung.model.lottery.LotteryItem;
import com.samsung.model.lottery.LotteryRecord;
import com.samsung.service.lottery.LotteryService;
/**
 * 
 * @ClassName: LotteryServiceImpl 
 * @Description: TODO(实现抽奖业务) 
 * @author hd1.zhao
 * @date 2015年5月14日 下午4:12:47  
 * @since
 */
@Service("lotteryService")
public class LotteryServiceImpl implements LotteryService {
	@Autowired
	private LotteryEventMapper lotteryEventMapper;
	@Autowired
	private  LotteryCandidateMapper lotteryCandidateMapper;
	@Autowired
	private  LotteryItemMapper lotteryItemMapper;
	@Autowired
	private LotteryRecordMapper lotteryRecordMapper;
	/**
	 * 查询抽奖事件实现
	 */
	public LotteryEvent getLotteryEvent(String lotteryEventId){
		return  lotteryEventMapper.selectByPrimaryKey(lotteryEventId);
	}
	/**
	 * 查询抽奖候选人实现
	 */	
	public List<CandidateDto> listByCandidate(String lotteryEventId){
		return lotteryCandidateMapper.selectCandidateByLid(lotteryEventId);
		
	}
	/**
	 * 查询抽奖项实现
	 */	
	public List<LotteryItem> listByItem( String lotteryEventId){
		return lotteryItemMapper.selectByLid(lotteryEventId);
	}
	public int saveLotteryRecord(LotteryRecord record){
		
		return lotteryRecordMapper.insertSelective(record);
		
	}
	/**
	 * 
	 * @Title: listNewLots 
	 * @Description: TODO(创建一个抽奖列表) 
	 * @param @return    设定文件 
	 * @return List<LotsEvent>    返回类型 
	 * @throws 
	 * @author rui1.liang
	 */
	@Override
	public List<LotteryEvent> listNewLottery(int max) {
		return lotteryEventMapper.listNewLottery(max);
	}
	
	/**
	 * 
	 * @Title: getRecordCount 
	 * @Description: TODO(获取抽奖记录，用于路由时判断是否抽过奖) 
	 * @param @param lotteryId
	 * @param @return    设定文件 
	 * @return int    返回类型 
	 * @throws 
	 * @author rui1.liang
	 */
	@Override
	public int getRecordCount(String lotteryId) {
		return lotteryRecordMapper.getRecordCount(lotteryId);
	}
	/**
	 * 插入一条抽奖信息
	 */
	@Override
	@Transactional
	public int insertNewLottery(EventFormDto eventFormDto) {
		/**
		 * 抽奖事件信息入库实现(ot_lottery_event)表
		 */
		String [] resultCandidate = eventFormDto.getCandidateList().split(",");
		LotteryEvent lotteryEvent = new LotteryEvent();
		if(eventFormDto != null){
			lotteryEvent.setId(BaseUtil.getUUID());
			eventFormDto.setId(lotteryEvent.getId());
			//获取标题
			lotteryEvent.setTitle(eventFormDto.getTitle());
			//获取抽奖类型
			lotteryEvent.setType(eventFormDto.getType());
			//获得新建抽奖者的Session
			lotteryEvent.setUid(eventFormDto.getUid());
			//修改时间格式
			lotteryEvent.setCreateTime(new Date());
			Date startTime = DateUtil.parseDateTime(eventFormDto.getStartTime());
			Date deadline = DateUtil.parseDateTime(eventFormDto.getDeadline());
			lotteryEvent.setStartTime(startTime);
			lotteryEvent.setDeadline(deadline);
			lotteryEventMapper.insert(lotteryEvent);
		}
		/**
		 * 抽奖候选人信息入库实现(ot_lottery_candidate)表
		 */
		if(resultCandidate != null){
			LotteryCandidate candidate = new LotteryCandidate();
			for(String result :resultCandidate ){
				candidate.setId(BaseUtil.getUUID());
				candidate.setLid(lotteryEvent.getId());
				if(!result.equals("")){
					candidate.setUid(result);
					lotteryCandidateMapper.insert(candidate);
				}
			}
		}
		/**
		 * 奖项列表信息入库实现(ot_lottery_item)表
		 */
		if(eventFormDto.getItems() != null){
			for (LotteryItem item : eventFormDto.getItems()) {
				item.setId(BaseUtil.getUUID());
				item.setLid(lotteryEvent.getId());
				lotteryItemMapper.insert(item);
			}
		}
		return 1;
	}
	/**
	 * 校验抽奖信息合法性的实现
	 */
	@Override
	public Map<String, Object> checkLotteryInfo(EventFormDto eventFormDto) {
		Map<String,Object> model = new HashMap<String, Object>();
		//抽奖时间信息校验
		if(BaseUtil.isEmpty(eventFormDto.getTitle())){
			model.put("message", "抽奖标题不能为空");
			model.put("flag", false);
			return model;
		} 
		if(eventFormDto.getTitle().length() > 20){
			model.put("message", "抽奖标题不能超过255个字符");
			model.put("flag", false);
			return model;
		}
		if (lotteryEventMapper.checkTitle(eventFormDto.getTitle()).size() > 0) {
			model.put("message", "活动名称存在，请重新命名");
			model.put("flag", false);
			return model;
		}
		if(!eventFormDto.getTitle().matches("^[\u4E00-\u9FFFA-Za-z0-9]*$")){
			model.put("message", "请输入合法的活动名称（汉字或字母数字的任意组合）");
			model.put("flag", false);
			return model;
		}
		if("".equals(eventFormDto.getStartTime()) || eventFormDto.getStartTime() == null){
			model.put("message", "开始时间不能为空");
			model.put("flag", false);
			return model;
		}
		if("".equals(eventFormDto.getDeadline()) || eventFormDto.getDeadline() == null){
			model.put("message", "结束时间不能为空");
			model.put("flag", false);
			return model;
		}
		if(DateUtil.parseDateTime(eventFormDto.getStartTime()).getTime() > DateUtil.parseDateTime(eventFormDto.getDeadline()).getTime()){
			model.put("message", "结束时间不能在开始时间之前");
			model.put("flag", false);
			return model;
		}
		//抽奖候选人信息校验
		String canStr = eventFormDto.getCandidateList();
		if(BaseUtil.isEmpty(canStr)) {
			model.put("message", "抽奖候选人不能为空");
			model.put("flag", false);
			return model;
		} 
		if(canStr!=null && canStr.trim().endsWith(",")) {
			eventFormDto.setCandidateList(canStr.substring(0, canStr.lastIndexOf(",")));
		}
		String [] resultCandidate = eventFormDto.getCandidateList().split(",");
		if("".equals(resultCandidate.toString())){
			//System.out.println(resultCandidate.length);
			model.put("message", "抽奖候选人不能为空");
			model.put("flag", false);
			return model;
		}
		//奖项信息校验
		for (int i=0; i<eventFormDto.getItems().size(); i++){
			if(eventFormDto.getItems().get(i).getTitle().length() == 0){
				model.put("message", "第"+(i+1)+"行奖项名称为空");
				model.put("flag", false);
				return model;
			}
			if(eventFormDto.getItems().get(i).getLotteryName().length() == 0){
				model.put("message", "第"+(i+1)+"行奖品名称为空");
				model.put("flag", false);
				return model;
			}
			if(eventFormDto.getItems().get(i).getTitle().length() > 255){
				model.put("message", "奖项名称"+i+"长度不能大于255");
				model.put("flag", false);
				return model;
			}
			if(eventFormDto.getItems().get(i).getLotteryName().length() > 255){
				model.put("message", "奖品名称"+i+"长度不能大于255");
				model.put("flag", false);
				return model;
			}
			if(!eventFormDto.getItems().get(i).getTitle().matches("^[\u4E00-\u9FFFA-Za-z0-9]*$")){
				model.put("message", "请输入合法的奖项名称（汉字或字母或数字）");
				model.put("flag", false);
				return model;
			}
			if(!eventFormDto.getItems().get(i).getLotteryName().matches("^[\u4E00-\u9FFFA-Za-z0-9]*$")){
				model.put("message", "请输入合法的奖品名称（汉字或字母或数字）");
				model.put("flag", false);
				return model;
			}
			//奖品数量校验
			if(eventFormDto.getItems().get(i).getAmount() == null){
				model.put("message", "第"+(i+1)+"项奖品数量为空(奖品数量不能为空)");
				model.put("flag", false);
				return model;
			}
			if( (eventFormDto.getItems().get(i).getAmount()==0)){
				model.put("message", "第"+(i+1)+"项奖品数量为0(奖品数量不能为0)");
				model.put("flag", false);
				return model;
			}
			if(eventFormDto.getItems().get(i).getAmount().toString().length() > 6){
				model.put("message", "第"+(i+1)+"项奖品数量过大(不能超过6位)");
				model.put("flag", false);
				return model;
			}
			Matcher matcherNum = Pattern.compile("^[0-9]*$").matcher(eventFormDto.getItems().get(i).getAmount().toString());
			if(!matcherNum.matches()){
				model.put("message", "请输入合法的数字");
				model.put("flag", false);
				return model;
			}
		}
		//奖项信息重复校验
		for (int i=0; i<eventFormDto.getItems().size(); i++){
			for (int j=1+i; j<eventFormDto.getItems().size(); j++) {
				if (eventFormDto.getItems().get(i).getTitle().equals(eventFormDto.getItems().get(j).getTitle())) {
					model.put("message", "奖项名称有重复，请重新设置");
					model.put("flag", false);
					return model;
				}
				if (eventFormDto.getItems().get(i).getLotteryName().equals(eventFormDto.getItems().get(j).getLotteryName())) {
					model.put("message", "奖品名称有重复，请重新设置");
					model.put("flag", false);
					return model;
				}
			}
		}
		//抽奖候选人数量和奖品数量校验
		int sum = 0;
		for(int i =0; i < eventFormDto.getItems().size(); i++){
			sum += eventFormDto.getItems().get(i).getAmount();
		}
		if(resultCandidate.length < sum){
			model.put("message", "奖品数量不能大于候选人数");
			model.put("flag", false);
			return model;
		}
		model.put("message", "保存成功");
		model.put("flag", true);
		return model;
	}
	/**
	 * 异步校验标题
	 */
	@Override
	public Map<String, Object> checkLotteryEvent(String title) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(BaseUtil.isEmpty(title)){
			result.put("message", "抽奖标题不能为空");
			result.put("flag", false);
			return result;
		} 
		if(title.length() > 20){
			result.put("message", "抽奖标题不能超过255个字符");
			result.put("flag", false);
			return result;
		}
		if (lotteryEventMapper.checkTitle(title).size() > 0) {
			result.put("message", "活动名称存在，请重新命名");
			result.put("flag", false);
			return result;
		}
		if(!title.matches("^[\u4E00-\u9FFFA-Za-z0-9]*$")){
			result.put("message", "请输入合法的活动名称（汉字或字母数字的任意组合）");
			result.put("flag", false);
			return result;
		}
		result.put("flag", true);
		return result;
	}
	@Override
	public List<ItemResultDto> listRecordByEvent(String lid) {
		return lotteryRecordMapper.listRecordByEvent(lid);
	}
	/* (non-Javadoc)
	 * @see com.samsung.service.lottery.LotteryService#getPageInfo(int, int)
	 */
	@Override
	public List<LotteryEvent> getPageInfo(int startPos, int pageSize) {
		Map<String, Integer> paramMap = new HashMap<String, Integer>();
		paramMap.put("startPos", startPos);
		paramMap.put("pageSize", pageSize);
		List<LotteryEvent> list=lotteryEventMapper.getPageInfo(paramMap);
		return list;
	}
	@Override
	public int delete(String lid) {
		lotteryRecordMapper.deleteByLid(lid);
		lotteryCandidateMapper.deleteByLid(lid);
		lotteryItemMapper.deleteByLid(lid);
		return lotteryEventMapper.deleteByPrimaryKey(lid);
	}
	@Override
	public int getTotalCount(String uid) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("uid", uid);
		return lotteryEventMapper.getTotalCount(paramMap);
	}
	
	/**
	 * 抽奖综合查询 wtj add
	 * @param paramMap
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getLotteryList(Map<String, Object> paramMap) {
		List<Map<String, Object>> list=lotteryEventMapper.getLotteryPageInfo(paramMap);
		return list;
	}
	
	@Override
	public int getLotteryListCount(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return lotteryEventMapper.getLotteryPageInfoCount(paramMap);
	}
	
	/**
	 * 抽奖发起查询
	 * @param startPos
	 * @param pageSize
	 * @param uid
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getMyCreatLotteryList(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return lotteryEventMapper.getCreateList(paramMap);
	}
	
	@Override
	public int getMyCreateCount(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return lotteryEventMapper.getCreateListCount(paramMap);
	}
	
}

